import { makeAutoObservable, runInAction } from "mobx";
import i18n from "i18n-js";
import AsyncStorage from "../utils/AsyncStorage";
import { Localization } from "../utils";
import { getAllLanguage, getLanguageKey } from "../language/tool";

/**
 * 初始化操作
 */
i18n.fallbacks = true;
i18n.translations = getAllLanguage();
i18n.defaultLocale = "zh";
i18n.locale = getLanguageKey();
i18n.missingTranslation = (key: string) => key;

export interface ILanguage {
  key: string;
  country: string;
  phoneCode: string;
  setCountry(data: { countryCode: string; phoneCode: string }): void;
  updateLanguage(key: string): void;
}

class Language implements ILanguage {
  constructor() {
    makeAutoObservable(this);
  }

  key: string = getLanguageKey();

  country: string = Localization.country();

  phoneCode: string = "+86";

  setCountry(data: { countryCode: string; phoneCode: string }) {
    console.log("setCountry => ", data);
    this.country = data.countryCode;
    this.phoneCode = data.phoneCode;
    AsyncStorage.setItem("countryCode", data.countryCode);
    AsyncStorage.setItem("phoneCode", data.phoneCode);
  }

  loadSubpackgesLanguage(json: any) {
    console.log(json)
    i18n.translations = Object.assign(i18n.translations, json)
    // console.log(i18n.translations)
  }

  updateLanguage(key: string) {
    i18n.locale = key;
    this.key = key;
    runInAction(async () => {
     await AsyncStorage.setItem("languageKey", key);
    })
  }

  // updateLanguage = flow(function* (this: Language, { key }) {
  //   console.log(key)
  //   yield AsyncStorage.setItem("languageKey", key);
  //   i18n.locale = key;
  //   this.key = key;
  // });
}

const Language_Store_Key = "language";

export { Language, Language_Store_Key };

export default new Language();
